package a66weding.com.jiehuntong.activity.me;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.CateguryGridViewBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MyOrderBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.fragment.order.AllOrderFragment;
import a66weding.com.jiehuntong.fragment.order.BaseOrderFragment;
import a66weding.com.jiehuntong.fragment.order.WaitEvaluationOrderFragment;
import a66weding.com.jiehuntong.fragment.order.WaitPayOrderFragment;
import a66weding.com.jiehuntong.fragment.order.WaitReceiptOrderFragment;
import a66weding.com.jiehuntong.fragment.order.WaitShipOrderFragment;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import me.imid.swipebacklayout.lib.SwipeBackLayout;

/**
 * 我的-订单界面
 * Created by Administrator on 2016/7/7.
 */
public class MeIndentActivity extends MeBaseActivity implements View.OnClickListener ,OnNetResultListener {
    private LinearLayout mBackLay;
    private TextView mBackContentTv;
    private TextView mHeaderTitleTv;
    private TextView mRightTitleTv;
    private PopupWindow mPopWindow;
    private ViewGroup mTitleLay;
    private View mContentLat;
    private View mProgressLay;
    private View mNoNetLay;
    private View mEmptyDataLay;
    private TabLayout mOrderTab;
    private ViewPager mOrderVpager;
    private List<CateguryGridViewBean.DataBean> mFiltrateList = new ArrayList<CateguryGridViewBean.DataBean>();
    private CateguryGridViewBean filtrateClassifyBean;
    private MeyAdapter meyAdapter;
    private boolean islogin;
    private int memberID;
    private List<BaseOrderFragment> fragmentlist = new ArrayList<>();
    private List<MyOrderBean.DataBean> orderList;
    private static final int GETDATASUCESS=1;
    private FragmentAdapter mFragAdapter;
    private List<String> mTitleList;
    private SwipeBackLayout mSwipeBackLayout;
    public static String orderDataBean="orderDataBean";
    private int mCurrentPager;
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
           switch (msg.what) {
                   case GETDATASUCESS:
                       initFragment();
                   break;
           }
        }
    };
    private int currentCategoryId;
    private boolean isShowError;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_indent);
        ((GlobalApplication)getApplication()).getActivityManager().addActivity("MeIndentActivity",this);
        mSwipeBackLayout=getSwipeBackLayout();
        mSwipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT);
        islogin=((GlobalApplication)getApplication()).isLogin();
        if(islogin){
            memberID = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
        }
        mTitleList=new ArrayList<String>();
        mTitleList.add("全部");
        mTitleList.add("待付款");
        mTitleList.add("待发货");
        mTitleList.add("待收货");
        mTitleList.add("待评价");
        initview();
        initData();
        getOrderData(0,1,0);
    }
    private void initview() {
        mBackLay = (LinearLayout) findViewById(R.id.lay_head_backlay);
        mBackContentTv = (TextView) findViewById(R.id.headleft_title_tv);
        mHeaderTitleTv = (TextView) findViewById(R.id.headcenter_title_tv);
        mRightTitleTv = (TextView) findViewById(R.id.headright_title_tv);
        mTitleLay = (ViewGroup) findViewById(R.id.rlay_title);
        mContentLat =  findViewById(R.id.lay_content);
        mProgressLay = (LinearLayout) findViewById(R.id.progressLay);
        mNoNetLay = (LinearLayout) findViewById(R.id.mNoNetLay);
        mEmptyDataLay =  findViewById(R.id.lay_emptydataLay);
        mOrderTab = (TabLayout) findViewById(R.id.tabs_order);
        mOrderVpager = (ViewPager) findViewById(R.id.viewpager_order);
        mRightTitleTv.setEnabled(true);
        mBackContentTv.setText("我的");
        mHeaderTitleTv.setText("我的订单");
        mRightTitleTv.setText("筛选");
        mBackLay.setOnClickListener(this);
        mRightTitleTv.setOnClickListener(this);
    }
    /**
     * 页面初始化数据调用的方法
     */
    private void initData() {
        // 请求筛选分类的请求
        String meUrl = RequestCode.GET_PRODUCTCATEGORYBYPID;
        HttpRequestBean httpRequestBeans = new HttpRequestBean(RequestCode.GETREQUEST,
                meUrl, this, CateguryGridViewBean.class, RequestCode.GET_PRODUCTCATEGORYBYPID);
        HttpHandleUtil.executeCommonGet(this, httpRequestBeans);
    }
    private void getOrderData(int category,int pagerIndex,int whereType){
        String orderUrl=RequestCode.get_MyOrderDetail;
        orderUrl += "&memberID="+memberID+"&category="+category+"&pageIndex="+pagerIndex+"&whereType="+whereType;
        HttpRequestBean httpRequestBeans = new HttpRequestBean(RequestCode.GETREQUEST,
                orderUrl, this, MyOrderBean.class, RequestCode.get_MyOrderDetail);
        HttpHandleUtil.executeCommonGet(this, httpRequestBeans);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
           case R.id.lay_head_backlay: //点击我的，返回到上一级界面
                finish();
                break;
            case R.id.headright_title_tv: //点击筛选，打开筛选窗体
                if (mPopWindow != null) {
                    mPopWindow.dismiss();
                    mPopWindow = null;
                }
                showPopupWindow(v);
                break;
        }
    }

    private  void initFragment(){
        AllOrderFragment orderFragment=new AllOrderFragment();
        WaitPayOrderFragment waitpayFragment=new WaitPayOrderFragment();
        WaitShipOrderFragment waitshipFragment=new WaitShipOrderFragment();
        WaitReceiptOrderFragment  waitReceiptFragment=new WaitReceiptOrderFragment();
        WaitEvaluationOrderFragment waitEvaluationFragment=new WaitEvaluationOrderFragment();
        fragmentlist.add(orderFragment);
        fragmentlist.add(waitpayFragment);
        fragmentlist.add(waitshipFragment);
        fragmentlist.add(waitReceiptFragment);
        fragmentlist.add(waitEvaluationFragment);
        mFragAdapter=new FragmentAdapter(getSupportFragmentManager(),mTitleList,fragmentlist);
        mOrderVpager.setAdapter(mFragAdapter);
        mOrderTab.setupWithViewPager(mOrderVpager);
        mOrderVpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }
            @Override
            public void onPageSelected(int position) {
                mCurrentPager=position;
            }
            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }
    //显示窗体
    private void showPopupWindow(View view) {
        //设置contentView
        View contentView = LayoutInflater.from(MeIndentActivity.this).inflate(R.layout.pop_filter_gridview, null);
        mPopWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.MATCH_PARENT, true);
        mPopWindow.setContentView(contentView);
        mPopWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.whitetranslucenthalf2)));
        //设置各个控件的点击响应
        GridView lv_popupwindow = (GridView) contentView.findViewById(R.id.grid_order_filter);
        meyAdapter = new MeyAdapter();
        lv_popupwindow.setAdapter(meyAdapter);
        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopWindow.dismiss();
            }
        });
        mPopWindow.showAsDropDown(mTitleLay);
    }
    private void notifydata(int currentCategoryId) {
        if(fragmentlist!=null && fragmentlist.size()>0) {
            fragmentlist.get(mCurrentPager).notifydata(currentCategoryId);
        }
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (data instanceof CateguryGridViewBean) {
            filtrateClassifyBean = (CateguryGridViewBean) data;
            mFiltrateList =  filtrateClassifyBean.getData();
            // 向集合中再添加一个元素
            CateguryGridViewBean.DataBean classifyBean = new CateguryGridViewBean.DataBean();
            classifyBean.setNvc_Name("全部");
            classifyBean.setI_Id(0);
            mFiltrateList.add(0,classifyBean);
        }else if(data instanceof MyOrderBean){
            MyOrderBean orderData= (MyOrderBean) data;
            switch (orderData.getResCode()) {
                    case "0000":
                        notifyViewLay(HAVEDATA);
                        orderList = orderData.getData();
                        mHandler.sendEmptyMessage(GETDATASUCESS);
                        break;
                     case "0003":
                         notifyViewLay(EMPTYDATA);
                    break;
            }
         }
    }

    @Override
    public void onError(ErrorBean errorBean) {
        switch (errorBean.getErrorCode()) {
                case ErrorBean.NONET:
                 case ErrorBean.TIMEOUT:
                     notifyViewLay(NONET);
                break;
                 case ErrorBean.DATAERROR:
                     CUtils.showDataErrToast(this);
                break;
                 default:
                     if(!isShowError){
                         CUtils.showDataErrToast(this);
                         isShowError=true;
                     }
        }
    }
    static class ViewHolder {
        RadioButton tv_listview_popupwindow;
    }
    class MeyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mFiltrateList.size();
        }
        @Override
        public Object getItem(int position) {
            return null;
        }
        @Override
        public long getItemId(int position) {
            return 0;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;
            ViewHolder holder;
            CateguryGridViewBean.DataBean dataBean = mFiltrateList.get(position);
            if (convertView != null) {
                view = convertView;
                holder = (ViewHolder) view.getTag();
            } else {
                view = View.inflate(getApplicationContext(), R.layout.item_order_filtrate, null);
                holder = new ViewHolder();
                holder.tv_listview_popupwindow = (RadioButton) view.findViewById(R.id.rbtn_defaultorder);
                view.setTag(holder);
            }
            holder.tv_listview_popupwindow.setText(mFiltrateList.get(position).getNvc_Name());

            boolean ischecked = dataBean.ischecked();

            if(ischecked) {
                holder.tv_listview_popupwindow.setChecked(true);
            }else{
                holder.tv_listview_popupwindow.setChecked(false);
            }

            holder.tv_listview_popupwindow.setTag(R.id.tag_first,position);
            holder.tv_listview_popupwindow.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int  position = (int) v.getTag(R.id.tag_first);
                    CateguryGridViewBean.DataBean dataBean = mFiltrateList.get(position);
                    if(dataBean.ischecked()) {

                    }else{
                        dataBean.setIschecked(true);
                        refreshBtnState(position,true);
                        //筛选
                        currentCategoryId = dataBean.getI_Id();
                        notifydata(currentCategoryId);

                        if (mPopWindow != null) {
                            mPopWindow.dismiss();
                            mPopWindow = null;
                        }
                    }
                }
            });
            return view;
        }
    }
    public class FragmentAdapter extends FragmentPagerAdapter {
        private List<String> mTitles;
        private List<BaseOrderFragment> fragmentlist;
        public FragmentAdapter(FragmentManager fm, List<String> titles, List<BaseOrderFragment> fragmentlist) {
            super(fm);
            this.mTitles = titles;
            this.fragmentlist=fragmentlist;
        }
        @Override
        public Fragment getItem(int position) {
            return fragmentlist.get(position);
        }
        @Override
        public int getCount() {
            return fragmentlist.size();
        }
        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles.get(position);
        }
        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }

    }

    public void refreshBtnState(int position,boolean ischecked){
        for (int i = 0; i < mFiltrateList.size(); i++) {
            if(i==position) {
                mFiltrateList.get(i).setIschecked(ischecked);
            }else{
                mFiltrateList.get(i).setIschecked(!ischecked);
            }
        }
        if(meyAdapter!=null) {
            meyAdapter.notifyDataSetChanged();
        }
    }
    private void notifyViewLay(int state){
        switch (state) {
            case HAVEDATA:
                mProgressLay.setVisibility(View.GONE);
                if(mContentLat.isShown()) {
                    return;
                }else{
                    mContentLat.setVisibility(View.VISIBLE);
                }
                mNoNetLay.setVisibility(View.GONE);
                mEmptyDataLay.setVisibility(View.GONE);
                break;
            case NODATA:
                mEmptyDataLay.setVisibility(View.VISIBLE);
                mRightTitleTv.setEnabled(false);
                mContentLat.setVisibility(View.GONE);
                mProgressLay.setVisibility(View.GONE);
                mNoNetLay.setVisibility(View.GONE);
                break;
            case NONET:
                mNoNetLay.setVisibility(View.VISIBLE);
                mContentLat.setVisibility(View.GONE);
                mProgressLay.setVisibility(View.GONE);
                mEmptyDataLay.setVisibility(View.GONE);
                break;
            case LOADINGDATA:
                mProgressLay.setVisibility(View.VISIBLE);
                break;
            case EMPTYDATA:
                mEmptyDataLay.setVisibility(View.VISIBLE);
                mContentLat.setVisibility(View.GONE);
                mProgressLay.setVisibility(View.GONE);
                mNoNetLay.setVisibility(View.GONE);
                break;
        }
    }
    public List<MyOrderBean.DataBean> getOrderList() {
        return orderList;
    }
    public int getMemberID() {
        return memberID;
    }
    public void setMemberID(int memberID) {
        this.memberID = memberID;
    }
    public int getCurrentCategoryId() {
        return currentCategoryId;
    }
}
